package com.studor.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.studor.common.Result;
import com.studor.entity.Student;
import com.studor.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/student")
public class StudentController {
    
    @Autowired
    private StudentService studentService;
    
    @GetMapping("/list")
    @SaCheckLogin
    public Result<List<Student>> list() {
        List<Student> students = studentService.list();
        return Result.success(students);
    }
    
    @GetMapping("/page")
    @SaCheckLogin
    public Result<IPage<Student>> page(@RequestParam(defaultValue = "1") Integer current,
                                       @RequestParam(defaultValue = "10") Integer size) {
        Page<Student> page = new Page<>(current, size);
        IPage<Student> result = studentService.page(page);
        return Result.success(result);
    }
    
    @GetMapping("/profile")
    @SaCheckLogin
    public Result<Student> getProfile() {
        Integer accountId = StpUtil.getLoginIdAsInt();
        Student student = studentService.getStudentByAccountId(accountId);
        return Result.success(student);
    }
    
    @PutMapping("/profile")
    @SaCheckLogin
    public Result<Void> updateProfile(@RequestBody Student student) {
        Integer accountId = StpUtil.getLoginIdAsInt();
        student.setId(accountId);
        studentService.updateById(student);
        return Result.success("更新个人信息成功");
    }
    
    @PostMapping("/select-room")
    @SaCheckLogin
    public Result<Void> selectRoom(@RequestBody Student student) {
        Integer accountId = StpUtil.getLoginIdAsInt();
        Student existingStudent = studentService.getStudentByAccountId(accountId);
        if (existingStudent != null) {
            existingStudent.setDormitory(student.getDormitory());
            existingStudent.setRoomNum(student.getRoomNum());
            existingStudent.setBedNum(student.getBedNum());
            studentService.updateById(existingStudent);
        }
        return Result.success("选择宿舍成功");
    }
} 